<template>
  <div class="songlist clearfix" v-ImglazyLoad>
    <div
      v-if="orderNew === true"
      style="
        height: 200px;
        font-size: 34px;
        text-align: center;
        line-height: 200px;
      "
    >
      网易云音乐的最新标签已经被去除，目前没有最新音乐的数据。
    </div>
    <template
      v-else
      v-for="(item, idnex) in currentSongData.playlists"
      :key="idnex"
    >
      <div class="songlist-li">
        <SongListItem :data="item"></SongListItem>
      </div>
    </template>
  </div>
  <MPage :curPageIdx="page" :pageSum="pageSum" @dirClick="pageClick"></MPage>
</template>
<script>
import { onMounted, reactive, toRefs, watch } from "vue";
import Service from "@/services";
import SongListItem from "./item";
import ImglazyLoad from "./directives/ImglazyLoad";
export default {
  name: "SongList",
  components: {
    SongListItem,
  },
  directives: {
    ImglazyLoad,
  },
  props: {
    cat: {
      type: String,
    },
    sort: {
      type: String,
    },
    itemid: {
      type: String,
    },
  },
  setup(props) {
    const service = new Service(),
      state = reactive({
        currentSongData: {},
        page: 1,
        pageSum: 0,
        limit: 20,
        orderNew: false,
      });

    onMounted(() => {
      setPlayLists();
    });

    // 监听categoryid、sortid 的变化 并获取新数据
    watch([() => props.cat, () => props.sort, () => props.itemid], () => {
      state.page = 1;
      setPlayLists();
    });

    const pageClick = (index) => {
      state.page = index;
      document.documentElement.scrollTop = 0;
      setPlayLists();
    };

    // 更新数据
    const setPlayLists = async () => {
      if (props.sort == "new") {
        state.orderNew = true;
        return;
      } else {
        state.orderNew = false;
      }

      if (props.itemid != "-1") {
        let data = await service.getSongList({
          cat: props.cat,
          tag: props.itemid,
          order: props.sort,
          limit: state.limit,
          offset: (state.page - 1) * state.limit,
        });

        state.currentSongData = data;
        state.pageSum = parseInt(state.currentSongData.total / 20);
      }
    };

    return {
      ...toRefs(state),
      pageClick,
    };
  },
};
</script>

<style lang='scss' scoped>
.songlist {
  position: relative;
  .songlist-li {
    float: left;
    width: 20%;
    margin-bottom: 20px;
  }
}
</style>
